package hadoop.reduceJoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {
        //该数组用于存储所有订单集合
        ArrayList<TableBean> orderBeans = new ArrayList<>();
        //该Bean对象用于存储产品信息
        TableBean pdBean = new TableBean();

        for (TableBean tableBean : values) {
            if ("order".equals(tableBean.getFlag())) {//如果是订单表
                //因为这里的tablebean只是一个引用而不是一个对象，所以需要创建一个TableBean对象，并把引用复制给它
                TableBean tmpBean = new TableBean();
                try {
                    BeanUtils.copyProperties(tmpBean, tableBean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                orderBeans.add(tmpBean);
            } else {//如果是产品表
                try {
                    //拷贝遍历到的产品表到pdBean中
                    BeanUtils.copyProperties(pdBean, tableBean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        //表的拼接
        for (TableBean tableBean1 : orderBeans) {
            tableBean1.setPname(pdBean.getPname());

            //把数据写出去
            context.write(tableBean1, NullWritable.get());
        }
    }
}



